/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mwt.xml.xdbforms.schemalayer.types;

import javax.xml.XMLConstants;
import mwt.xml.xdbforms.dblayer.metadata.impl.ColumnMetaData;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;

/**
 * Progetto Master Web Technology.
 *
 * Gestisce il tipo BINARY del database, come uno stream
 * di bit. Viene usato il tipo base base64binary di lunghezza
 * variabile
 *
 * @author Gianfranco Murador, Cristian Castiglia, Matteo Ferri
 */
public class XmlBinary extends XmlTypes {

    public XmlBinary() {
    }

    /**
     * Costruttore ereditato
     * @param doc documento xschema da costruire
     */
    public XmlBinary(Document doc) {
        super(doc);
    }

    /**
     * Costruisce il frammento
     */
    private void buildFragment(ColumnMetaData cmd) {
        Element xtype, restriction, maxLength;
        fragment = doc.createDocumentFragment();
        Integer length = cmd.getDisplaySize();
       

        xtype = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:simpleType");
        xtype.setAttribute("name", typeName+"_"+length);
        cmd.setXschemaTypeName(typeName+"_"+length);

        restriction = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:restriction");
        restriction.setAttribute("base", "xs:base64Binary");

        maxLength = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:maxLength");

        maxLength.setAttribute("value", length.toString());

        xtype.appendChild(restriction);
        restriction.appendChild(maxLength);
        fragment.appendChild(xtype);
    }

    @Override
    public DocumentFragment getSchemaType(ColumnMetaData cmd) {

        typeName = cmd.getTypeName();

        if (typeName.equals("BINARY")) {

            buildFragment(cmd);
            return fragment;

        }


        // The last ring of the chain

        return null;

    }

    @Override
    public Object getXSchemaToJavaType(String baseType, String value) {

        if (baseType.startsWith("BINARY")) {

            Byte b = new Byte(value);
  
   
            return b;
        } else {

            return null;
        }
    }
}
